package com.petHis.project.system.records.service.impl;

import java.math.BigDecimal;
import java.util.List;
import com.petHis.common.utils.DateUtils;
import com.petHis.common.utils.security.ShiroUtils;
//import com.petHis.project.monitor.online.domain.OnlineSession;
import com.petHis.project.system.financial.domain.FinancialRecord;
import com.petHis.project.system.financial.mapper.FinancialRecordMapper;
import com.petHis.project.system.inventory.domain.DrugInventory;
import com.petHis.project.system.inventory.mapper.DrugInventoryMapper;
import com.petHis.project.system.record.domain.MedicationRecord;
import com.petHis.project.system.record.mapper.MedicationRecordMapper;
import com.petHis.project.system.user.domain.UserRole;
import com.petHis.project.system.user.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.petHis.project.system.records.mapper.MedicalRecordsMapper;
import com.petHis.project.system.records.domain.MedicalRecords;
import com.petHis.project.system.records.service.IMedicalRecordsService;
import com.petHis.common.utils.text.Convert;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.http.HttpServletRequest;

/**
 * 诊疗记录Service业务层处理
 * 
 * @author petHis
 * @date 2025-02-16
 */
@Service
public class MedicalRecordsServiceImpl implements IMedicalRecordsService 
{
    @Autowired
    private MedicalRecordsMapper medicalRecordsMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private MedicationRecordMapper medicationMapper;

    @Autowired
    private FinancialRecordMapper financialRecordMapper;

    @Autowired
    private DrugInventoryMapper drugInventoryMapper;

    /**
     * 查询诊疗记录
     * 
     * @param recordId 诊疗记录主键
     * @return 诊疗记录
     */
    @Override
    public MedicalRecords selectMedicalRecordsByRecordId(Long recordId)
    {
        return medicalRecordsMapper.selectMedicalRecordsByRecordId(recordId);
    }

    /**
     * 查询诊疗记录列表
     * 
     * @param medicalRecords 诊疗记录
     * @return 诊疗记录
     */
    @Override
    public List<MedicalRecords> selectMedicalRecordsList(MedicalRecords medicalRecords)
    {
        List<UserRole> userRoles = userRoleMapper.selectUserRoleByUserId(ShiroUtils.getUserId());
//        System.out.println("-----------------------juese");
//        System.out.println(userRoles);
        if (!userRoles.isEmpty()){
//            获取第一个对象里的roleId
            Long roleId = userRoles.get(0).getRoleId();
            if (roleId==2){
                medicalRecords.setCreateBy(ShiroUtils.getLoginName());
                System.out.println(medicalRecords);
            }
        }
        return medicalRecordsMapper.selectMedicalRecordsList(medicalRecords);
    }

    /**
     * 新增诊疗记录
     * 
     * @param medicalRecords 诊疗记录
     * @return 结果
     */
//    @Override
    public int insertMedicalRecords(MedicalRecords medicalRecords, HttpServletRequest request)
    {
        medicalRecords.setCreateTime(DateUtils.getNowDate());
        medicalRecords.setCreateBy(ShiroUtils.getLoginName());
//        调用 mapper 方法插入诊疗信息
        return medicalRecordsMapper.insertMedicalRecords(medicalRecords);
    }

    /**
     * 修改诊疗记录
     * 
     * @param medicalRecords 诊疗记录
     * @return 结果
     */
    @Override
    public int updateMedicalRecords(MedicalRecords medicalRecords)
    {
        System.out.println("------------------edit zhenliao");
        System.out.println(medicalRecords);
        // 1. 更新诊疗主表
        int rows = medicalRecordsMapper.updateMedicalRecords(medicalRecords);

//        2、新增用药记录
        List<MedicationRecord> medicationList = medicalRecords.getMedications();

        if (medicationList != null && !medicationList.isEmpty()){
            for (MedicationRecord medicationRecord : medicationList){
                try {
                    // 插入用药记录
                    medicationMapper.insertMedicationRecord(medicationRecord);

//                    修改库存信息
                    DrugInventory drugInventory = new DrugInventory();
                    drugInventory.setDrugId(medicationRecord.getDrugId());
                    DrugInventory oldDrugInventory = drugInventoryMapper.selectDrugInventoryByDrugId(medicationRecord.getDrugId());
                    long newStockQuantity = oldDrugInventory.getStockQuantity() - medicationRecord.getTotalQuantity();
                    drugInventory.setStockQuantity(newStockQuantity);
                    System.out.println("----newStockQuantity");
                    System.out.println(drugInventory);
                    drugInventoryMapper.updateDrugInventory(drugInventory);
                } catch (DuplicateKeyException e) {
                    // 处理重复插入的情况，可根据需求进行日志记录或其他操作
                    System.out.println("重复插入用药记录：recordId=" + medicationRecord.getRecordId() + ", drugId=" + medicationRecord.getDrugId());
                }
            }

            // 创建财务记录
            FinancialRecord financialRecord = new FinancialRecord();
            financialRecord.setDictCode(3L);
            financialRecord.setAmount(medicalRecords.getCost());
            financialRecord.setRecordDate(DateUtils.getNowDate());
            financialRecord.setRelatedId(medicalRecords.getRecordId());
            String remark = "新增收入： 就诊医生（" +medicalRecords.getCreateBy()+ ")；宠物姓名（"+medicalRecords.getPetName()+"）；诊断结果（"+medicalRecords.getDiagnosis()+")；";
            financialRecord.setRemark(remark);

            // 插入财务记录
            financialRecordMapper.insertFinancialRecord(financialRecord);
        }

        return rows;
    }

    /**
     * 批量删除诊疗记录
     * 
     * @param recordIds 需要删除的诊疗记录主键
     * @return 结果
     */
    @Override
    public int deleteMedicalRecordsByRecordIds(String recordIds)
    {
        return medicalRecordsMapper.deleteMedicalRecordsByRecordIds(Convert.toStrArray(recordIds));
    }

    /**
     * 删除诊疗记录信息
     * 
     * @param recordId 诊疗记录主键
     * @return 结果
     */
    @Override
    public int deleteMedicalRecordsByRecordId(Long recordId)
    {
        return medicalRecordsMapper.deleteMedicalRecordsByRecordId(recordId);
    }


}
